// 数据统计页面
const auth = require('../../../utils/auth')
const userApi = require('../../../api/user')
const minLivingAllowanceApi = require('../../../api/minLivingAllowance')
const complaintsApi = require('../../../api/complaints')
const activitiesApi = require('../../../api/activities')

Page({
  data: {
    userInfo: {},
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    loading: true,
    
    // 数据更新时间
    lastUpdateTime: '',
    
    // 概览数据
    overviewStats: {
      totalUsers: 0,
      totalServices: 0,
      totalActivities: 0,
      totalCases: 0,
      todayUsers: 0,
      todayServices: 0,
      weekGrowth: 0
    }
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.loadUserInfo()
    this.loadStatsData()
  },

  onShow() {
    this.loadStatsData()
  },

  // 加载用户信息
  loadUserInfo() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      // 开发阶段：临时允许访问，但显示提示
      wx.showToast({
        title: '请以管理员身份登录',
        icon: 'none',
        duration: 2000
      })
      
      // 设置临时用户信息用于演示
      const tempUserInfo = {
        name: '演示管理员',
        role: 'admin',
        village: '七里营村'
      }
      this.setData({ userInfo: tempUserInfo })
      return
    }
    
    const userInfo = wx.getStorageSync('USER_INFO') || {}
    this.setData({ userInfo })
  },

  // 加载统计数据
  async loadStatsData() {
    this.setData({ loading: true })
    this.showGlobalLoading('正在加载统计数据...')
    
    try {
      // 并行获取所有统计数据
      const [
        userStats,
        userCount,
        serviceStats,
        complaintStats,
        activityStats
      ] = await Promise.allSettled([
        this.loadUserStats(),
        this.loadUserCount(),
        this.loadServiceStats(),
        this.loadComplaintStats(),
        this.loadActivityStats()
      ])

      // 检查各个API调用结果
      const results = {
        userStats: userStats.status === 'fulfilled' ? userStats.value : null,
        userCount: userCount.status === 'fulfilled' ? userCount.value : null,
        serviceStats: serviceStats.status === 'fulfilled' ? serviceStats.value : null,
        complaintStats: complaintStats.status === 'fulfilled' ? complaintStats.value : null,
        activityStats: activityStats.status === 'fulfilled' ? activityStats.value : null
      }

      // 整合所有数据
      const overviewStats = {
        totalUsers: results.userCount?.data?.totalCount || 0,
        totalServices: results.serviceStats?.data?.totalApplications || 0,
        totalActivities: results.activityStats?.data?.totalActivities || 0,
        totalCases: (results.complaintStats?.data?.pendingCount || 0) + (results.serviceStats?.data?.pendingApplications || 0),
        todayUsers: results.userCount?.data?.todayNewTotalCount || 0,
        todayServices: results.serviceStats?.data?.todayApplications || 0,
        weekGrowth: this.calculateWeekGrowth(results.userStats?.data)
      }
      
      // 记录数据更新时间
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const updateTime = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`
      
      console.log('数据更新时间设置为:', updateTime)
      
      this.setData({ 
        overviewStats,
        lastUpdateTime: updateTime,
        loading: false 
      })
      
      this.hideGlobalLoading()
      
      // 显示成功提示（可选）
      console.log('统计数据加载成功:', overviewStats)
      
    } catch (error) {
      console.error('加载统计数据失败:', error)
      this.hideGlobalLoading()
      this.setData({ loading: false })
      
      // 显示错误提示
      wx.showModal({
        title: '数据加载失败',
        content: '无法获取最新统计数据，请检查网络连接后重试',
        showCancel: true,
        cancelText: '取消',
        confirmText: '重试',
        success: (res) => {
          if (res.confirm) {
            this.loadStatsData()
          }
        }
      })
    }
  },

  // 加载用户统计数据
  async loadUserStats() {
    try {
      return await userApi.getUserStats()
    } catch (error) {
      console.error('获取用户统计失败:', error)
      return { data: {} }
    }
  },

  // 加载用户总数量
  async loadUserCount() {
    try {
      return await userApi.getUserCount()
    } catch (error) {
      console.error('获取用户数量失败:', error)
      return { data: { totalCount: 0, todayNewTotalCount: 0 } }
    }
  },

  // 加载服务事项统计数据
  async loadServiceStats() {
    try {
      // 获取所有申请列表来统计
      const result = await minLivingAllowanceApi.getAllApplications({
        page: 1,
        limit: 1
      })
      
      if (result.success) {
        const totalApplications = result.data.pagination.total
        const applications = result.data.applications || []
        
        // 统计今日申请
        const today = new Date().toISOString().split('T')[0]
        const todayApplications = applications.filter(app => 
          app.applyTime && app.applyTime.startsWith(today)
        ).length
        
        // 统计待处理申请
        const pendingApplications = applications.filter(app => 
          app.status === 'pending'
        ).length
        
        return {
          data: {
            totalApplications,
            todayApplications,
            pendingApplications
          }
        }
      }
      
      return { data: { totalApplications: 0, todayApplications: 0, pendingApplications: 0 } }
    } catch (error) {
      console.error('获取服务统计失败:', error)
      return { data: { totalApplications: 0, todayApplications: 0, pendingApplications: 0 } }
    }
  },

  // 加载投诉建议统计数据
  async loadComplaintStats() {
    try {
      const result = await complaintsApi.getAdminComplaintStats()
      
      if (result.success) {
        return {
          data: {
            pendingCount: result.data.pendingCount || 0,
            totalCount: result.data.totalCount || 0
          }
        }
      }
      
      return { data: { pendingCount: 0, totalCount: 0 } }
    } catch (error) {
      console.error('获取投诉统计失败:', error)
      return { data: { pendingCount: 0, totalCount: 0 } }
    }
  },

  // 加载活动统计数据
  async loadActivityStats() {
    try {
      const result = await activitiesApi.getActiveActivities({
        page: 1,
        limit: 1
      })
      
      if (result.success) {
        return {
          data: {
            totalActivities: result.data.pagination?.total || 0
          }
        }
      }
      
      return { data: { totalActivities: 0 } }
    } catch (error) {
      console.error('获取活动统计失败:', error)
      return { data: { totalActivities: 0 } }
    }
  },

  // 计算周增长率
  calculateWeekGrowth(userStats) {
    if (!userStats) return 0
    
    const { activeUsers, totalUsers } = userStats
    if (!activeUsers || !totalUsers || totalUsers === 0) return 0
    
    // 简单的增长率计算（实际项目中可能需要更复杂的计算）
    const growthRate = ((activeUsers / totalUsers) * 100).toFixed(1)
    return parseFloat(growthRate)
  },



  // 导航到图表分析页面
  navigateToChartAnalysis() {
    wx.navigateTo({
      url: '/pages/admin/chart-analysis/index'
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    console.log('开始下拉刷新...')
    try {
      await this.loadStatsData()
      console.log('下拉刷新成功，数据已更新')
    } catch (error) {
      console.error('下拉刷新失败:', error)
      wx.showToast({
        title: '刷新失败，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.stopPullDownRefresh()
    }
  },

  // 手动刷新数据
  async refreshData() {
    try {
      await this.loadStatsData()
    } catch (error) {
      console.error('手动刷新失败:', error)
      wx.showToast({
        title: '刷新失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 格式化数字显示
  formatNumber(num) {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万'
    }
    return num.toString()
  },

})
